﻿using System.Linq;
using GNSCore.Helpers;
using GNSCore.Managers;
using GNSCore.Model;
using GNSCore.Repositories;
using GNSCore.Repositories.IOC;
using GNSCore.Model.Context;

namespace GNSCore.Managers
{
    /// <summary>
    /// For managin location
    /// </summary>
    public class LocationManger
    {
        private IRepository<Model.Location> _locationRep;
        
        /// <summary>
        /// Default constructor for creating object graph
        /// </summary>
        public LocationManger()
        {
        }

        /// <summary>
        /// Constr with concrete repository implementation paramenter
        /// </summary>
        /// <param name="_rep"></param>
        public LocationManger(IRepository<Location> _rep)
        {
            _locationRep = _rep;
        }
        /// <summary>
        /// Saves new user location to the data base
        /// </summary>
        /// <param name="latitude">Latitude</param>
        /// <param name="longitude">Longitude</param>
        /// <param name="radius">Radius, to search events</param>
        /// <param name="username">User identifier</param>
        /// <returns>Saved location identifier</returns>
        public int SaveLocationForUser(double latitude, double longitude, double radius, string username)
        {
            User currentUser = _locationRep.GetAll<User>().FirstOrDefault(us => us.UserName == username);
            var location = new Location();
            location.Latitude = latitude;
            location.Longitude = longitude;
            location.Radius = radius;
            location.User = currentUser;
            _locationRep.Add(location);
            _locationRep.SaveChanges(true);
            return location.ID;
        }

        /// <summary>
        /// Returns user location
        /// </summary>
        /// <param name="username">Username (user identifier)</param>
        /// <returns>User's location</returnst>
        public Location GetLocationForUser(string username)
        {
            return _locationRep.GetAll<Location>().FirstOrDefault(loc => loc.User.UserName == username);
        }
    }
}